<template>
  <div class="student">
    <h2>学生姓名: {{ name }}</h2>
    <h2>学生性别: {{ gender }}</h2>
    <button @click="sendStudentMessage">点我传递学生信息</button>
    <button @click="unbindSubscribe">解绑订阅的事件</button>
    <p>要入学的学校信息: {{ schoolMessage }}</p>
  </div>
</template>

<script>
// 引入 pubsub 第三方库用于 消息订阅与发布
import pubsub from "pubsub-js";

export default {
  name: "student-name",
  data() {
    return {
      name: "张三",
      gender: "男",
      schoolMessage: "",
    };
  },
  methods: {
    sendStudentMessage() {
      console.log("查看组件实例vc:", this);
      pubsub.publish("getStudent-message", [this.name, this.gender]);
    },
    unbindSubscribe() {
      this.$destroy();
    },
  },
  mounted() {
    this.getSchoolMessage = pubsub.subscribe("getSchool-message", (_, data) => {
      this.schoolMessage = data;
    });
  },
  beforeDestroy() {
    console.log(111);
    pubsub.unsubscribe([this.getSchoolMessage]);
  },
};
</script>

<style lang="less" scoped>
.student {
  background-color: skyblue;
  padding: 10px;
  margin: 10px;
}
</style>
